using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;

public class AudionManager : MonoBehaviour
{
    public static AudionManager instance;

    [SerializeField] private float sfxMinDistance;
    [SerializeField] private AudioSource[] sfx;
    [SerializeField] private AudioSource[] bgm;

    public bool isPlayBGM;
    public int bgmIndex;

    private void Awake()
    {
        if (instance != null)       //����Ѿ�����ʵ����������������ǰ���󣬲�����ʵ��������
        {
            Destroy(instance.gameObject);
            instance = this;
        }
        else instance = this;
    }

    private void Update()
    {
        if(!isPlayBGM) 
        {
            StopAllBGM();
        }
        else
        {
            if (!bgm[bgmIndex].isPlaying) 
            {
                PlayBGM(bgmIndex);
            }
        }
    }

    public void PlaySFX(int _sfxIndex, Transform _source)
    {
        if (sfx[_sfxIndex].isPlaying)
            return;

        if (_source != null && Vector2.Distance(PlayerManager.instance.player.transform.position, _source.position) > sfxMinDistance)
            return;

        if(_sfxIndex < sfx.Length) 
        {
            sfx[_sfxIndex].Play();
        }
    }

    public void StopSFX(int _sfxIndex) => sfx[_sfxIndex].Stop();

    public void PlayBGM(int _bgmIndex)
    {
        bgmIndex = _bgmIndex;

        StopAllBGM();
        bgm[bgmIndex].Play();
    }

    public void StopAllBGM()
    {
        for(int i =  0; i < bgm.Length; i++) 
        {
            bgm[i].Stop();
        }
    }
}
